package com.example.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.generator.domain.Order;
import com.example.generator.domain.Salesman;
import com.example.generator.service.OrderService;
import com.example.generator.service.SalesmanService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：chengyoubang
 * @version ：V1.0
 * @program ：hmall
 * @date ：Created in 2024/11/13 11:39
 * @description ：
 */
@Component
public class InitOrderTask {

    @Resource
    OrderService orderService;

    @Resource
    SalesmanService salesmanService;
    @Scheduled(cron = "0 0/1 * * * ?")
    public void scheduledTask() {
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        List<Order> list = orderService.list(new LambdaQueryWrapper<Order>().eq(Order::getOrderDate, dateStr).orderByAsc(Order::getSalesmanId));
        if (CollectionUtils.isEmpty(list)) {
            List<Salesman> salesmanList = salesmanService.list(new LambdaQueryWrapper<Salesman>().orderByAsc(Salesman::getSortId));
            list = new ArrayList<>();
            for (Salesman salesman : salesmanList) {
                Order order = new Order();
                order.setSalesmanId(salesman.getSalesmanId());
                order.setSalesmanName(salesman.getSalesmanName());
                order.setAddTime(new Date());
                order.setUpdateTime(new Date());
                order.setOrderDate(dateStr);
                order.setSortId(salesman.getSortId());
                list.add(order);
            }
            orderService.saveBatch(list);
        }
    }
}

